package 二叉树;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution145 {
    public static void main(String[] args) {
        Node left = new Node(null, null, 4);
        Node right = new Node(null, null, 3);
        Node node = new Node(left, right, 2);
        List<Integer> list = postorderTraversal(node);
        System.out.println(list);

    }


    /**
     * 后序遍历
     *
     * @param root
     * @return
     */
    public static List<Integer> postorderTraversal(Node root) {
        List<Integer> arr = new ArrayList<>();
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {

            Node pop = stack.pop();
            if (pop == null) {
                break;
            }
            arr.add(pop.value);
            if (pop.right != null) {
                arr.add(pop.right.value);
            }
            if (pop.left != null) {
                arr.add(pop.left.value);
            }

        }
        Collections.reverse(arr);
        return arr;
    }
}
